// 获取下级菜单
const getSubMenus = async (pId, permission) => {
  const container = []
  const walker = async (pId) => {
    const parent = new Parse.Object('Menu')
    parent.id = pId
    const subMenus = await new Parse.Query('Menu').equalTo('parent', parent).find(permission)
    container.push(...subMenus)
    if (subMenus && subMenus.length > 0) {
      for (let i = 0, len = subMenus.length; i < len; i++) {
        await walker(subMenus[i].id)
      }
    }
  }
  await walker(pId)
  return container
}

Parse.Cloud.define('editMenu', async (req, res) => {
  const user = req.user
  if (!user) {
    return res.error('请先登录')
  }
  const permission = { sessionToken: user.getSessionToken() }

  const { id, name, path, icon, seq, parentId, roles } = req.params
  if (!name) {
    return res.error('请填写菜单名')
  }

  try {
    // 修改
    if (id) {
      const current = await new Parse.Query('Menu').equalTo('objectId', id).first(permission)
      if (!current) {
        return res.error('没有该菜单')
      }
      console.log('current', current)
      current.set('name', name).set('path', path).set('icon', icon).set('seq', seq)
      const menus = []
      menus.push(current)
      // 如果为顶级菜单，更改权限时，子菜单的权限也更改
      if (!current.get('parent') && roles && roles.length > 0) {
        const subMenus = await getSubMenus(current.id, permission)
        menus.push(...subMenus)
        const menuACL = new Parse.ACL()
        menuACL.setPublicReadAccess(false)
        menuACL.setPublicWriteAccess(false)
        menuACL.setRoleReadAccess('Admin', true)
        menuACL.setRoleWriteAccess('Admin', true)
        roles.forEach((role) => {
          menuACL.setRoleReadAccess(role, true)
        })
        menus.forEach((menu) => {
          menu.setACL(menuACL)
        })
      }
      await Parse.Object.saveAll(menus, permission)
    } else {  // 新增
      let parentMenu
      if (parentId) {
        parentMenu = await new Parse.Query('Menu').equalTo('objectId', parentId).first(permission)
      }

      let menuACL
      if (parentMenu) {  // 如果有父级，则子菜单的权限跟父级菜单一致
        menuACL = parentMenu.getACL()
      } else {  // 如果没有父级，则根据roles来设置
        menuACL = new Parse.ACL()
        menuACL.setPublicReadAccess(false)
        menuACL.setPublicWriteAccess(false)
        menuACL.setRoleReadAccess('Admin', true)
        menuACL.setRoleWriteAccess('Admin', true)

        if (roles && roles.length > 0) {
          roles.forEach((role) => {
            menuACL.setRoleReadAccess(role, true)
          })
        }
      }
      const Menu = Parse.Object.extend('Menu')
      const menu = new Menu({
        name,
        path,
        icon,
        seq,
        parent: parentMenu
      })

      menu.setACL(menuACL)

      await menu.save(null, permission)
    }

    res.success('ok')
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }

})
